package org.cloud.im.admin.common.filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: w.weidong.lin@abite.com
 * @Description: 权限过滤
 * @Date: create in 2021/10/26 21:01
 */
@Component
@Order(5)
@WebFilter(urlPatterns = "/", filterName = "authFilter")
public class AuthFilter implements Filter {

    private Logger logger = LogManager.getLogger(AuthFilter.class.getName());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("authFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletResponse response1 = response;
        HttpServletRequest request1 = request;
        String originHeader = request.getHeader("Origin");
//        if (originHeader != null && webConfigProperties.getAllowOrigin().contains(originHeader)) {
        //跨域检查空请求
        response1.setHeader("Access-Control-Allow-Origin", originHeader);
//        }

        response.setHeader("Access-Control-Allow-Credentials", "true");
        response1.setHeader("Access-Control-Allow-Headers", "Authentication,Origin,X-Requested-With,x-requested-with,X-Session-Token,x-session-token,X-Token, X-Requested-With, Content-Type, Accept,");
        response1.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        if (request1.getMethod().equals(RequestMethod.OPTIONS.toString())) {
            response1.setHeader("Access-Control-Expose-Headers", "*");
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        logger.info("authFilter destroy");
    }
}
